package lol.oxguy3.birthdaycounter;

import java.util.Calendar;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;

public class BirthdayCounterActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Button monthbtn = (Button) findViewById(R.id.buttonMonth);
        Button daybtn = (Button) findViewById(R.id.buttonDay);
        Button yearbtn = (Button) findViewById(R.id.buttonYear);
        
        OnClickListener buttonClickListener = new OnClickListener(){

			public void onClick(View v) {
				String buttonname = ((Button)v).getText().toString();
				respondToButton(buttonname);
			}
        	
        };
        
        monthbtn.setOnClickListener(buttonClickListener);
        daybtn.setOnClickListener(buttonClickListener);
        yearbtn.setOnClickListener(buttonClickListener);
        
    }
    
    public void respondToButton(String btnname) {
    	
    	DatePicker datePicker = (DatePicker) findViewById(R.id.datePickerMain);
    	
    	Calendar calendar = Calendar.getInstance();
    	
    	int currentmonth = calendar.get(Calendar.MONTH) + 1; //N.B. range is 0-11 not 1-12
    	int currentday = calendar.get(Calendar.DAY_OF_MONTH); //starts at 1
    	int currentyear = calendar.get(Calendar.YEAR);
    	
    	int currentdayofyear = calendar.get(Calendar.DAY_OF_YEAR);
    	
    	
    	Calendar usercal = Calendar.getInstance();
    	usercal.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth());
    	
    	int usermonth =  usercal.get(Calendar.MONTH) + 1;
    	int userday = usercal.get(Calendar.DAY_OF_MONTH);
    	int useryear = usercal.get(Calendar.YEAR);
    	
    	int userdayofyear = usercal.get(Calendar.DAY_OF_YEAR);
    	
    	
    	//int userdayofyear = datePicker.
    	
    	
    	int diffmonths = currentmonth-usermonth;
    	int diffdays = currentday-userday;
    	int diffyears = currentyear-useryear;
    	
    	int diffdaysofyear = currentdayofyear-userdayofyear;
    	
    	double total = -1;
    	
    	if (btnname.equals("Month")) {
    		total = diffmonths + (12*diffyears) + (diffdays/30);
    		
    	} else if (btnname.equals("Day")) {
    		total = diffdaysofyear + (365*diffyears);
    		
    	} else if (btnname.equals("Year")) {
    		total = diffyears + (diffdaysofyear/365);
    		
    	}
    	TextView textViewOutput = (TextView) findViewById(R.id.textViewOutput);
    	textViewOutput.setText("It has been "+Double.valueOf(total)+" "+btnname.toLowerCase()+"(s)!");
    }
}